"""阿里百炼平台LLM提供商"""

import os
from typing import List, Dict, Any, Optional
from openai import OpenAI
from dotenv import load_dotenv


class BailianProvider:
    """阿里百炼平台LLM提供商"""
    
    def __init__(self, api_key: str = None):
        """初始化百炼提供商"""
        load_dotenv()
        self.api_key = api_key or os.getenv("DASHSCOPE_API_KEY")
        self.client = OpenAI(
            api_key=self.api_key,
            base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
        )
    
    def chat_completion(self, messages: List[Dict[str, str]], model: str = "qwen-plus", **kwargs) -> Any:
        """聊天完成接口"""
        return self.client.chat.completions.create(
            model=model,
            messages=messages,
            **kwargs
        )
    
    def stream_chat(self, messages: List[Dict[str, str]], model: str = "qwq-plus", **kwargs) -> Any:
        """流式聊天接口"""
        return self.client.chat.completions.create(
            model=model,
            messages=messages,
            stream=True,
            **kwargs
        )
    
    def get_available_models(self) -> List[str]:
        """获取可用模型列表"""
        return [
            "qwen-plus",
            "qwen-max", 
            "qwen-turbo",
            "qwq-plus",
            "qwen3-30b-a3b-thinking-2507",
            "qwen3-235b-a22b-thinking-2507"
        ]


# 向后兼容的函数
def create_bailian_client():
    """创建百炼客户端（向后兼容）"""
    return BailianProvider()


def test_bailian():
    """测试百炼API"""
    try:
        provider = BailianProvider()
        
        messages = [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "你是谁？"},
        ]
        
        completion = provider.chat_completion(messages)
        print("百炼API测试成功！")
        print(completion.model_dump_json())
        
    except Exception as e:
        print(f"百炼API测试失败: {e}")


if __name__ == "__main__":
    test_bailian()